package com.treeliked.netdiskdemo.listener;

import com.aliyun.oss.event.ProgressEvent;
import com.aliyun.oss.event.ProgressEventType;
import com.aliyun.oss.event.ProgressListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 对象存储上传文件进度监听
 *
 * @author lqs2
 * @date 2018-12-15, Sat
 */
public class PutObjectProgressListener implements ProgressListener {


    private static Logger log = LoggerFactory.getLogger(PutObjectProgressListener.class);
    private long bytesWritten = 0;
    private long totalBytes;
    private boolean succeed = false;

    public PutObjectProgressListener(long totalBytes) {
        this.totalBytes = totalBytes;
    }

    @Override
    public void progressChanged(ProgressEvent progressEvent) {
        long bytes = progressEvent.getBytes();
        ProgressEventType eventType = progressEvent.getEventType();
        switch (eventType) {
            case TRANSFER_STARTED_EVENT:
                log.info("Request Start...");
                break;
            case REQUEST_CONTENT_LENGTH_EVENT:
                this.totalBytes = bytes;
                break;
            case REQUEST_BYTE_TRANSFER_EVENT:
                this.bytesWritten += bytes;
                if (this.totalBytes != -1) {
                    int percent = (int) (this.bytesWritten * 100.0 / this.totalBytes);
                    log.info("{} bytes have been written at this time, upload progress: {}% ({}/{})", bytes, percent, this.bytesWritten, this.totalBytes);
                } else {
                    log.info("{} bytes have been written at this time,  upload ratio: unknown ({}/{})", bytes, this.bytesWritten, this.totalBytes);
                }
                break;
            case TRANSFER_COMPLETED_EVENT:
                this.succeed = true;
                log.info("Succeed to upload, {}  bytes have been transferred in total" + this.bytesWritten);
                break;
            case TRANSFER_FAILED_EVENT:
                log.info("Failed to upload,  {}  bytes have been transferred." + this.bytesWritten);
                break;
            default:
                break;
        }
    }

    /**
     * 是否上传成功
     */
    public boolean isSucceed() {
        return succeed;
    }
}
